<?php


namespace App\Http\Controllers\Admin;
use App\Http\Controllers\BaseController;
use App\Models\Banner;
use Illuminate\Http\Request;

class BannerController extends BaseController
{
    /**
     * 列表
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request) {
        $start_at = $request->input('start_at');
        $end_at = $request->input('end_at');
        $type = $request->input('type');
        $users = Banner::when($start_at, function ($q) use($start_at){
            $q->where('created_at', '>=', $start_at);
        })->when($end_at, function ($q) use($end_at){
            $end_at = date('Y-m-d', strtotime($end_at) + 24 * 3600);
            $q->where('created_at', '<=', $end_at);
        })->type($type)->orderBy('sort', 'desc')->orderBy("id", "desc")
            ->paginate(\request('per_page', 20));
        return $this->paginate($users);
    }

    /**
     * 详情
     * @param Request $request
     * @return mixed
     * @throws \Illuminate\Validation\ValidationException
     */
    public function info(Request $request) {
        $this->validate($request, [
            'id' => 'required|exists:banner'
        ]);
        $id = \request("id");
        $info = Banner::find($id);
        return $this->success($info);
    }

    /**
     * 保存|修改
     * @param Request $request
     * @return mixed
     * @throws \Illuminate\Validation\ValidationException
     */
    public function store(Request $request) {
        $this->validate($request, [
            'logo' => 'required',
            'sort' => 'filled|integer',
            'id' => 'filled|exists:banner'
        ]);
        $input = $request->input();
        $id = \request("id");
        if ($id) {
            $banner = Banner::where('id', $id)->first();
            $banner->update($input);
        } else {
            $info = Banner::create($input);
            $id = $info->id;
        }
        return $this->success($id);
    }

    public function destroy(Request $request) {
        $this->validate($request, [
            'id' => 'required|exists:banner'
        ]);
        $id = $request->input('id');
        Banner::where('id', $id)->first()->delete();
        return $this->success([]);
    }


}

